import type { Router } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import NProgress from "@/utils/progress";
import { removeToken, getTokenValue, multipleTabsKey } from "@/utils/auth";
import {
  getTopMenu,
  isOneOfArray,
  findRouteByPath,
  handleAliveRoute
} from "./utils";
import { isUrl, openLink, isAllEmpty } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { getConfig } from "@/config";
import Cookies from "js-cookie";

/** 路由白名单 */
const whiteList = ["/login"];

const { VITE_HIDE_HOME } = import.meta.env;

const handleTagsCacheAfterReresh = (to: ToRouteType, router: Router) => {
  if (!useMultiTagsStoreHook().getMultiTagsCache) {
    const { path } = to;
    console.log(
      "to route",
      to,
      router.getRoutes(),
      router.options.routes[0].children
    );
    const route = findRouteByPath(path, router.getRoutes());
    getTopMenu(true);
    // query、params模式路由传参数的标签页不在此处处理
    if (route && route.meta?.title) {
      const { path, name, meta } = route;
      useMultiTagsStoreHook().handleTags("push", {
        path,
        name,
        meta
      });
    }
  }
};

export function setupRouterHooks(router: Router) {
  router.beforeEach(async (to: ToRouteType, _from, next) => {
    if (to.meta?.keepAlive) {
      handleAliveRoute(to, "add");
      // 页面整体刷新和点击标签页刷新
      if (_from.name === undefined || _from.name === "Redirect") {
        handleAliveRoute(to);
      }
    }
    const userStore = useUserStore();
    NProgress.start();
    let tokenValue = getTokenValue();
    if (tokenValue) {
      if (userStore.getUserid === "0" || userStore.getUserid === "") {
        await userStore.getUserInfo().then(res => {
          if (res && res.code !== 200) {
            removeToken();
            next({ path: "/login" });
            return;
          }
        });
      }
      const externalLink = isUrl(to?.name as string);
      if (!externalLink) {
        to.matched.some(item => {
          if (!item.meta.title) return "";
          const Title = getConfig().Title;
          if (Title) document.title = `${item.meta.title} | ${Title}`;
          else document.title = item.meta.title as string;
        });
      }
      /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
      function toCorrectRoute() {
        if (whiteList.includes(to.fullPath)) {
          next(_from.fullPath);
        } else {
          next();
        }
      }
      if (Cookies.get(multipleTabsKey) && userStore) {
        // 无权限跳转403页面
        if (to.meta?.roles && !isOneOfArray(to.meta?.roles, userStore?.roles)) {
          next({ path: "/error/403" });
        }
        // 开启隐藏首页后在浏览器地址栏手动输入首页welcome路由则跳转到404页面
        if (VITE_HIDE_HOME === "true" && to.fullPath === "/welcome") {
          next({ path: "/error/404" });
        }
        if (_from?.name) {
          // name为超链接
          if (externalLink) {
            openLink(to?.name as string);
            NProgress.done();
          } else {
            toCorrectRoute();
          }
        } else {
          // 刷新
          if (
            usePermissionStoreHook().wholeMenus.length === 0 &&
            to.path !== "/login"
          ) {
            await usePermissionStoreHook().loadRouter();
          }
          handleTagsCacheAfterReresh(to, router);
          if (isAllEmpty(to.name)) router.push(to.fullPath);
          toCorrectRoute();
        }
      }
    } else {
      if (to.path !== "/login") {
        if (whiteList.indexOf(to.path) !== -1) {
          next();
        } else {
          const userStore = useUserStore();
          userStore.resetAll();
          next({ path: "/login" });
        }
      } else {
        next();
      }
    }
  });
  router.afterEach(() => {
    NProgress.done();
  });
}
